﻿KISSY.use("validation, fgt/auth, fgt/ui", function (S, Validation, Auth, UI) {
    S.ready(function (S) {
        var $ = S.all,
            J = jQuery,
            form = $("#J_Pricing"),
            VALID_EFFECT = "Simple",
            VALID_STYLE = "s_b",
            validator = new Validation(form[0], { warn: VALID_EFFECT, style: VALID_STYLE }),
            submitBtn = $("#J_Sumbit"),
            moreBtns = $("#J_Pricing .more-btn"),
            addItemizedChargeBtn = $("#J_AddItemizedCharge"),
            itemizedChargeList = form.all(".itemized-charge-list"),
            nameInputs = itemizedChargeList.all(".name"),
            chargeInputs = itemizedChargeList.all(".charge"),
            popbox = UI.getPopbox();

        validator.add("#rental_rate_daily",
        {
            required: [false],
            regex: [/^\d+(\.\d+)?$/, 'Must be numeric.'],
            moreThan: [0, "Must be more than {0}."]
        });

        validator.add("#rental_rate_weekly",
        {
            required: [false],
            regex: [/^\d+(\.\d+)?$/, 'Must be numeric.'],
            moreThan: [0, "Must be more than {0}."]
        });

        validator.add("#rental_rate_monthly",
        {
            required: [false],
            regex: [/^\d+(\.\d+)?$/, 'Must be numeric.'],
            moreThan: [0, "Must be more than {0}."]
        });

        validator.add("#milage_free_miles_daily",
        {
            required: [false],
            regex: [/^\d+$/, 'Must be numeric.'],
            moreThan: [0, "Must be more than {0}."]
        });

        validator.add("#milage_free_miles_weekly",
        {
            required: [false],
            regex: [/^\d+$/, 'Must be numeric.'],
            moreThan: [0, "Must be more than {0}."]
        });

        validator.add("#milage_free_miles_monthly",
        {
            required: [false],
            regex: [/^\d+$/, 'Must be numeric.'],
            moreThan: [0, "Must be more than {0}."]
        });

        validator.add("#milage_per_extra_mile_daily",
        {
            required: [false],
            regex: [/^\d+(\.\d+)?$/, 'Must be numeric.'],
            moreThan: [0, "Must be more than {0}."]
        });

        validator.add("#milage_per_extra_mile_weekly",
        {
            required: [false],
            regex: [/^\d+(\.\d+)?$/, 'Must be numeric.'],
            moreThan: [0, "Must be more than {0}."]
        });

        validator.add("#milage_per_extra_mile_monthly",
        {
            required: [false],
            regex: [/^\d+(\.\d+)?$/, 'Must be numeric.'],
            moreThan: [0, "Must be more than {0}."]
        });

        validator.add("#deposit_nonrefundable_security_down_payment",
        {
            required: [false],
            regex: [/^\d+(\.\d+)?$/, 'Must be numeric.'],
            moreThan: [0, "Must be more than {0}."]
        });
        validator.add("#deposit_refundable_damage_protection",
        {
            required: [false],
            regex: [/^\d+(\.\d+)?$/, 'Must be numeric.'],
            moreThan: [0, "Must be more than {0}."]
        });
        validator.add("#deposit_refundable_cleaning_charge",
        {
            required: [false],
            regex: [/^\d+(\.\d+)?$/, 'Must be numeric.'],
            moreThan: [0, "Must be more than {0}."]
        });
        validator.add("#late_charge_per_hour",
        {
            required: [false],
            regex: [/^\d+(\.\d+)?$/, 'Must be numeric.'],
            moreThan: [0, "Must be more than {0}."]
        });
        S.each(nameInputs, function (input) {
            validator.add("#" + $(input).attr("id"),
            {
                required: [true, "Name is required."],
                maxLength: [100, true, "At most 100 characters."]
            });
        });
        S.each(chargeInputs, function (input) {
            validator.add("#" + $(input).attr("id"),
            {
                required: [true, "Charge is required."],
                regex: [/^\d+(\.\d+)?$/, 'Must be numeric.'],
                moreThan: [0, "Must be more than {0}."]
            });
        });

        function submit() {
            Auth.validate(function () {
                try {
                    var paramStr = S.ajax.serialize(form),
                        resultCode = FGT.core.constant.jsonResultCode,
                        failureText = "Save failure, please try again later.",
                        delay = 1000;

                    J.ajax({
                        url: "/rv/save/pricing",
                        type: "POST",
                        data: paramStr,
                        beforeSend: function (jqXHR, settings) {
                            submitBtn.prop("disabled", true);
                            popbox.show("Saving");
                        },
                        success: function (data, textStatus, jqXHR) {
                            if (data.Result === resultCode.SUCCESS) {
                                popbox.show(data.Content, delay);
                            }
                            else {
                                var jsonData = data.Content;
                                if (S.isString(jsonData)) {
                                    popbox.show(jsonData, delay);
                                }
                                else if (S.isArray(jsonData)) {
                                    S.each(jsonData, function (item) {
                                        var target = $(item.id);
                                        if (target.attr("data-msgbox")) {
                                            var label = $(target.attr("data-msgbox"));
                                            if (label) {
                                                label.text(item.msg);
                                                label.removeClass("ok tip error");
                                                label.addClass("error");
                                                label.show();
                                            }
                                        }
                                    });
                                    popbox.hide();
                                }
                                submitBtn.prop("disabled", false);
                            }
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            submitBtn.prop("disabled", false);
                            popbox.show(failureText, delay);
                        }
                    });
                }
                catch (e) {
                    popbox.show(failureText, delay);
                    submitBtn.prop("disabled", false);
                }
            }, popbox, this);
        }

        submitBtn.on("click", function (event) {
            event.halt();
            var self = this,
                b = validator.isValid();
            if (b === true) {
                submit();
            }
        });

        moreBtns.on("click", function (event) {
            event.halt();
            var self = $(this);
            if (self.attr("data-more-id")) {
                var more = $("#" + self.attr("data-more-id"));
                if (more) {
                    self.hide();
                    more.show();
                }
            }
        });

        addItemizedChargeBtn.on("click", function (event) {
            event.halt();

            var index = S.guid(),
                labelId = "ic_name_" + index,
                labelName = "itemizedCharges[" + index + "].Name",
                labelMsgId = "msg_ic_name_" + index,
                labelMsgId2 = "#" + labelMsgId,
                chargeId = "ic_charge_" + index,
                chargeName = "itemizedCharges[" + index + "].Charge",
                chargeMsgId = "msg_ic_charge_" + index,
                chargeMsgId2 = "#" + chargeMsgId,
                frequenceId = "ic_freq_" + index,
                frequenceName = "itemizedCharges[" + index + "].Frequence",
                deleteOnclickStr = "func.deleteItemizedCharge('" + labelId + "', '" + chargeId + "', this); return false;";

            var html = "<li class='row clearfix'>"
                        + "<input type='hidden' name='itemizedCharges.Index' value='" + index + "' />"
                        + "<div class='input'>"
                            + "<input id='" + labelId + "' class='input-text name' type='text' name='" + labelName + "' data-msgbox='" + labelMsgId2 + "'/>"
                            + "<p id='" + labelMsgId + "' style='display: none;'></p>"
                        + "</div>"
                        + "<span class='unit'>for</span>"
                        + "<span class='money'>$</span>"
                        + "<div class='input'>"
                            + "<input id='" + chargeId + "' class='input-text charge' type='text' name='" + chargeName + "' data-msgbox='" + chargeMsgId2 + "'/>"
                            + "<p id='" + chargeMsgId + "' style='display: none;'></p>"
                        + "</div>"
                        + "<select id='" + frequenceId + "' class='select' name='" + frequenceName + "'>"
                            + "<option value='0' selected='selected'>One time</option>"
                            + "<option value='1'>Daily</option>"
                            + "<option value='2'>Weekly</option>"
                            + "<option value='3'>Monthly</option>"
                        + "</select>"
                        + '<a  class="delete" href="javascript:;" onclick="' + deleteOnclickStr + '">Delete</a>'
                    + "</li>";

            itemizedChargeList.append(html);

            validator.add("#" + labelId,
            {
                required: [true, "Name is required."],
                maxLength: [100, true, "At most 100 characters."]
            });

            validator.add("#" + chargeId,
            {
                required: [true, "Charge is required."],
                regex: [/^\d+(\.\d+)?$/, 'Must be numeric.'],
                moreThan: [0, "Must be more than {0}."]
            });
        });

        S.mix(func, {
            deleteItemizedCharge: function (labelId, chargeId, target) {
                var $ = S.all,
                    listItem = $(target);

                validator.remove(labelId);
                validator.remove(chargeId);
                listItem.parent(".row").remove();
            }
        });

    });
});